%%%-------------------------------------------------------------------
%%% File    : util.erl
%%% Author  :  <vjache>
%%% Description : 
%%%
%%% Created : 21 Apr 2009 by  <vjache>
%%%-------------------------------------------------------------------
-module(util).

-include("../include/valg.hrl").
-include("../include/test.hrl").

%% API
-export([
		 map_triples2spo/1,
		 map_triples2pso/1,
		 map_triples2osp/1,
		 map_from_file/3,
		 wait_finish/1,
		 wait_finish_ex/1
		 ]).

%%====================================================================
%% API
%%====================================================================
%%--------------------------------------------------------------------
%% Function: 
%% Description:
%%--------------------------------------------------------------------
map_triples2spo(Config) ->
	_Pid=map_from_file(?CONFIG(data_dir,Config)++"/triple.txt",vect_mnesia:new_mem_bag(t_spo, [subj,pred,obj]),
				  fun({S,P,O})->
						  {t_spo,S,P,O}
				  end).

map_triples2pso(Config) ->
	_Pid=map_from_file(?CONFIG(data_dir,Config)++"/triple.txt",vect_mnesia:new_mem_bag(t_pso, [pred,subj,obj]),
				  fun({S,P,O})->
						  {t_pso,P,S,O}
				  end).

map_triples2osp(Config) ->
	_Pid=map_from_file(?CONFIG(data_dir,Config)++"/triple.txt",vect_mnesia:new_mem_bag(t_osp, [obj,subj,pred]),
				  fun({S,P,O})->
						  {t_osp,O,S,P}
				  end).

map_from_file(Filename,Vect,RecFun) ->
	Rs={?RS_TAG,iter_term_reader:new_from_file(Filename)},
	MapExpr1 = {?MAP_TAG, 
				Rs , 
				RecFun},
	pgt:new(valg:eval(MapExpr1, pipe_vect:new(Vect))).

wait_finish(Pid) when is_pid(Pid)->
	Ref=erlang:monitor(process, Pid),
	receive
		{'DOWN', Ref, _Type, _Object, _Info} ->
			ok
	end;
wait_finish(Pids) when is_list(Pids)->
	Refs=[erlang:monitor(process, Pid)||Pid<-Pids],
	wf_rc_loop(Refs).

wf_rc_loop([]) ->
	?CT_LOG_INFO("WORK FINISH ALL~n",[]),
	ok;
wf_rc_loop([Ref|Tail]=_Refs) ->
	receive
		{'DOWN', Ref, _Type, _Object, _Info}=DBG ->
			?CT_LOG_INFO("WORK FINISH ~p~n",[DBG]),
			wf_rc_loop(Tail)
	end.
wait_finish_ex(PidFunList) when is_list(PidFunList)->
	RefFunList=[{erlang:monitor(process, Pid),Fun}||{Pid,Fun}<-PidFunList],
	wfex_rc_loop(RefFunList).

wfex_rc_loop([]) ->
	ok;
wfex_rc_loop(RefFunList) ->
	receive
		{'DOWN', Ref, _Type, _Object, _Info} ->
			{value,{Ref,Fun},RefFunList1}=lists:keytake(Ref, 1, RefFunList),
			Fun(),
			wfex_rc_loop(RefFunList1)
	end.

%%====================================================================
%% Internal functions
%%====================================================================


